package cuit.blog.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.ui.Model;
import cuit.blog.entity.Article;
import cuit.blog.entity.Reply;
import cuit.blog.service.ArticleService;
import cuit.blog.service.ReplyService;
import jakarta.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("")
public class IndexController {
	@Autowired
	ReplyService replyService;
	@Autowired
	ArticleService articleService;

	@GetMapping("/index")
	public String login(Model model) {
		Optional<Article> article = articleService.findRandomArticle();
		article.ifPresent(a -> {  
	        Long id = a.getId(); // 假设 getId() 是 Article 类中的方法  
	        // 根据文章的id查找回复  
	        List<Reply>  replies = replyService.findByArticle_id(id);  
	        model.addAttribute("indexreplies", replies); // 将回复添加到模型中  
	        model.addAttribute("indexarticle", a); // 将文章添加到模型中  
	    }); 
		return "index";
	}
	@GetMapping("/root/index")
	public String rootLogin() {
		return "root/index";
	}
	@GetMapping("/logout")
	public String logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return "login";
	}
}
